/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 * Copyright (C) 2016-2020 the AndroidAnnotations project
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.internal.core.handler;

import com.helger.jcodemodel.IJAssignmentTarget;
import com.helger.jcodemodel.IJExpression;
import com.helger.jcodemodel.JBlock;
import com.helger.jcodemodel.JMethod;

import org.ohosannotations.ElementValidation;
import org.ohosannotations.OhosAnnotationsEnvironment;
import org.ohosannotations.handler.MethodInjectionHandler;
import org.ohosannotations.helper.CanonicalNameConstants;
import org.ohosannotations.helper.InjectHelper;
import org.ohosannotations.holder.EComponentWithViewSupportHolder;
import org.ohosannotations.holder.EFractionHolder;

import java.lang.annotation.Annotation;

import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;

import static com.helger.jcodemodel.JExpr.cast;
import static com.helger.jcodemodel.JExpr.invoke;

/**
 * 文摘部分通过处理程序
 *
 * @author dev
 * @since 2021-07-22
 */
public abstract class AbstractFractionByHandler extends CoreBaseAnnotationHandler<EComponentWithViewSupportHolder>
    implements MethodInjectionHandler<EComponentWithViewSupportHolder> {
    private final InjectHelper<EComponentWithViewSupportHolder> injectHelper;

    private Class<? extends Annotation> targetClass;

    /**
     * 发现分数方法名称
     */
    protected String findFractionMethodName;

    /**
     * 文摘部分通过处理程序
     *
     * @param targetClass 目标类
     * @param environment 环境
     * @param findFractionMethodName 发现分数方法名称
     */
    public AbstractFractionByHandler(Class<? extends Annotation> targetClass,
        OhosAnnotationsEnvironment environment, String findFractionMethodName) {
        super(targetClass, environment);
        this.targetClass = targetClass;
        this.findFractionMethodName = findFractionMethodName;
        injectHelper = new InjectHelper<>(validatorHelper, this);
    }

    @Override
    protected void validate(Element element, ElementValidation validation) {
        injectHelper.validate(targetClass, element, validation);
        if (!validation.isValid()) {
            return;
        }

        Element param = element;
        if (element instanceof ExecutableElement) {
            param = ((ExecutableElement) element).getParameters().get(0);
        }
        validatorHelper.extendsFraction(param, validation);

        validatorHelper.isNotPrivate(element, validation);

        coreValidatorHelper.childFragmentUsedOnlyIfEnclosingClassIsFragment(element, validation);

        if (validation.isValid()) {
            coreValidatorHelper.getChildFragmentManagerMethodIsAvailable(element, validation);
        }
    }

    /**
     * process
     *
     * @param element element
     * @param holder holder
     * @throws Exception
     */
    @Override
    public final void process(Element element, EComponentWithViewSupportHolder holder) throws Exception {
        injectHelper.process(element, holder);
    }

    /**
     * getInvocationBlock
     *
     * @param holder holder
     * @return holder
     */
    @Override
    public JBlock getInvocationBlock(EComponentWithViewSupportHolder holder) {
        return holder.getOnViewChangedBodyInjectionBlock();
    }

    /**
     * assignValue
     *
     * @param targetBlock targetBlock
     * @param fieldRef fieldRef
     * @param holder holder
     * @param element element
     * @param param param
     */
    @Override
    public void assignValue(JBlock targetBlock, IJAssignmentTarget fieldRef,
                            EComponentWithViewSupportHolder holder, Element element, Element param) {
        TypeMirror elementType = param.asType();
        String typeQualifiedName = elementType.toString();
        TypeElement nativeFractionElement = annotationHelper
            .typeElementFromQualifiedName(CanonicalNameConstants.FRACTION);
        boolean isNativeFragment = nativeFractionElement != null && annotationHelper
            .isSubtype(elementType, nativeFractionElement.asType());

        String fieldName = element.getSimpleName().toString();

        if (holder instanceof EFractionHolder) {
            boolean childFraction = annotationHelper
                .extractAnnotationParameter(element, "childFraction");

            String fractionManagerGetter = childFraction ? "getChildFractionManager" : "getFractionManager";

            targetBlock.add(fieldRef.assign(cast(getJClass(typeQualifiedName), invoke(fractionManagerGetter)
                .invoke(findFractionMethodName).arg(getFractionId(element, fieldName)))));
        } else {
            JMethod findFractionMethod = getFindFractionMethod(isNativeFragment, holder);

            targetBlock.add(fieldRef.assign(cast(getJClass(typeQualifiedName),
                invoke(findFractionMethod).arg(getFractionId(element, fieldName)))));
        }
    }

    /**
     * validateEnclosingElement
     *
     * @param element element
     * @param valid valid
     */
    @Override
    public void validateEnclosingElement(Element element, ElementValidation valid) {
        validatorHelper.enclosingElementHasEnhancedViewSupportAnnotation(element, valid);
    }

    /**
     * getFindFractionMethod
     *
     * @param isNativeFraction isNativeFraction
     * @param holder holder
     * @return null
     */
    protected abstract JMethod getFindFractionMethod(boolean isNativeFraction, EComponentWithViewSupportHolder holder);

    /**
     * getFractionId
     *
     * @param element element
     * @param fieldName fieldName
     * @return null
     */
    protected abstract IJExpression getFractionId(Element element, String fieldName);
}
